import Vue from 'vue';
import Router from 'vue-router';
import Login from './views/Login.vue';
import Home from './views/Home.vue';
import PublicActivities from './views/PublicActivities.vue';
import ActivityDetail from './views/ActivityDetail.vue';
import ActivityManagement from './views/ActivityManagement.vue';

const router = new Router({
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: Login
    },
    {
      path: '/',
      name: 'Home',
      component: Home,
      children: [
        {
          path: 'public-activities',
          name: 'PublicActivities',
          component: PublicActivities,
          meta: { requiresAuth: true } // 新增认证要求
        },
        {
          path: 'public-activities/:id',
          name: 'ActivityDetail',
          component: ActivityDetail,
          meta: { requiresAuth: true } // 新增认证要求
        }
      ],
      meta: { requiresAuth: true }
    },
    // 活动管理路由提升为顶级路由以支持独享守卫
    {
      path: '/activity-management',
      name: 'ActivityManagement',
      component: ActivityManagement,
      meta: { requiresAuth: true }
    }
  ]
});

// 全局前置路由守卫
router.beforeEach((to, from, next) => {
  const userRole = localStorage.getItem('userRole');

  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!userRole) {
      next({ path: '/login' });
    } else {
      // 检查是否是访问 /activity-management 并且不是管理员
      if (to.path === '/activity-management' && userRole !== 'admin') {
        alert('您没有权限访问该页面');
        next({ path: '/' }); // 阻止访问并返回首页
      } else {
        next();
      }
    }
  } else {
    next();
  }
});

export default router;